<template>
	<main-content
		:tableHeight.sync="tableHeight"
		:otherDependenComponents="otherDependenComponents"
	>
		<template slot="query">
			<el-form
				ref="formRef"
				:inline="true"
				:model="queryData"
				class="flex-warp-container"
			>
				<!--				<el-form-item-->
				<!--					:label="$t('common.belong_merchant') + ':'"-->
				<!--					class="flex-row-container"-->
				<!--					label-width="77px"-->
				<!--				>-->
				<!--					<merchant-select-->
				<!--						v-model="queryData.merchantId"-->
				<!--						:merchantInfo.sync="merchantObj"-->
				<!--					></merchant-select>-->
				<!--				</el-form-item>-->
				<el-form-item class="flex-row-container">
					<el-select
						v-model="dateFlag"
						style="width:140px"
						:placeholder="$t('common.please_choose')"
					>
						<el-option
							:label="$t('report.real_time_data')"
							value="1"
						/>
						<el-option
							:label="$t('report.statistics_data')"
							value="0"
						/>
					</el-select>
					<el-date-picker
						v-model="searchTime"
						type="daterange"
						range-separator="-"
						:start-placeholder="$t('report.start_date')"
						:end-placeholder="$t('report.end_date')"
						:picker-options="pickerShortcutWithCurrPeriod"
						:clearable="false"
						:disabled="isAllData"
					></el-date-picker>
				</el-form-item>
				<!-- <el-form-item
						:label="$t('report.register_date') + ':'"
						class="flex-row-container"
						label-width="77px"
					>
						<el-date-picker
							v-model="registerTime"
							type="daterange"
							range-separator="-"
							:start-placeholder="$t('report.start_date')"
							:end-placeholder="$t('report.end_date')"
							:picker-options="pickerShortcut3"
							:clearable="false"
						></el-date-picker>
					</el-form-item> -->
				<el-form-item
					:label="$t('common.agent_number') + ':'"
					class="flex-row-container"
					label-width="77px"
				>
					<el-input
						v-model.trim="queryData.proxyName"
						:maxlength="11"
						clearable
						autocomplete="off"
						v-symbols
						oninput="value=value.replace(/[\u4E00-\u9FA5]/g ,'')"
						:placeholder="$t('common.please_enter')"
					></el-input>
				</el-form-item>
				<el-form-item
					:label="$t('common.direct_superior') + ':'"
					class="flex-row-container"
					label-width="77px"
				>
					<el-input
						v-model.trim="queryData.parentProxyName"
						clearable
						size="medium"
						:maxlength="11"
						:placeholder="$t('report.please_input')"
						:disabled="loading"
						autocomplete="off"
						v-symbols
						oninput="value=value.replace(/[\u4E00-\u9FA5]/g ,'')"
						@keyup.enter.native="enterSearch"
					></el-input>
				</el-form-item>
				<el-form-item
					:label="`${$t('common.number_type')}:`"
					class="flex-row-container"
					label-width="77px"
				>
					<el-select
						v-model="queryData.accountType"
						size="medium"
						:placeholder="$t('common.select_all')"
						clearable
						collapse-tags
					>
						<el-option
							v-for="item in accountTypeArr"
							:key="item.code"
							:label="item.description"
							:value="item.code"
						></el-option>
					</el-select>
				</el-form-item>
				<el-form-item>
					<el-button
						type="primary"
						icon="el-icon-search"
						size="medium"
						@click="search"
					>
						{{ $t('common.search') }}
					</el-button>
					<el-button
						icon="el-icon-refresh-left"
						size="medium"
						@click="reset"
					>
						{{ $t('common.reset') }}
					</el-button>
					<el-button
						v-if="hasPermission('702021')"
						type="warning"
						icon="el-icon-download"
						size="medium"
						:loading="exportBtnLoading"
						@click="handleExportExcel"
					>
						{{ $t('common.export') }}
					</el-button>
					<el-button
						type="success"
						icon="el-icon-sort"
						:disabled="loading"
						size="medium"
						@click="openColSettings"
					>
						{{ $t('common.row_set') }}
					</el-button>
				</el-form-item>
				<date-picker-shortcuts
					kind="shortcutForButtons"
					:action="handleShortcutBtnClick"
					:loading="loading || dateFlag === '1'"
				/>
			</el-form>
			<el-link :underline="false" type="danger">
				{{ $t('report.refresh_warning_text') }}
			</el-link>
		</template>
		<template slot="content">
			<el-table
				v-loading="loading"
				ref="elTable"
				border
				size="mini"
				show-summary
				:data="tableData"
				style="width: 100%"
				:max-height="tableHeight"
				:default-sort="{
					prop: 'registerAt',
					order: 'descending'
				}"
				:key="headKey"
				v-bind="$attrs"
				v-on="$listeners"
				:cell-class-name="cellClassName"
				:header-cell-class-name="cellClassName"
				@sort-change="changeTableSort"
				class="small-size-table"
				:header-cell-style="getRowClass"
				element-loading-spinner="el-icon-loading"
				highlight-current-row
				:summary-method="
					(val) => handleRow(val, subSummary, totalSummary)
				"
			>
				<el-table-column
					v-for="(item, index) in newCol"
					:key="'column_' + index"
					:prop="newCol[index].prop"
					:align="item.alignCenter"
					:label="item.label"
					:min-width="item.minWidth"
					:fixed="item.isFixed"
					:sortable="item.isSortColumn"
					:show-overflow-tooltip="item.isShowTip"
				>
					<template slot="header" slot-scope="{ column, $index }">
						<span
							v-if="item.soltHeraer"
							@mousedown="
								handleMounseDown($event, column, $index)
							"
							@dragover="handleDragover($event, column, $index)"
						>
							{{ $t(newCol[index].label) }}
							<br />
							{{ $t(newCol[index].subLabel) }}
						</span>
						<span
							v-else
							@mousedown="
								handleMounseDown($event, column, $index)
							"
							@dragover="handleDragover($event, column, $index)"
						>
							{{ item.label }}
						</span>
					</template>
					<template slot-scope="{ row }">
						<Copy
							v-if="item.solt === 'copySolt'"
							:title="row[newCol[index].prop]"
							:copy="copy"
							:textColor="item.userColor"
							@click="dialogData(1, row)"
						>
							{{ row[newCol[index].prop] }}
						</Copy>
						<Copy
							v-if="item.solt === 'copyDefaultSolt'"
							:title="row[newCol[index].prop]"
							:copy="copy"
						>
							{{ row[newCol[index].prop] }}
						</Copy>
						<div v-if="item.solt === 'filterType'">
							{{
								typeFilter(
									row[newCol[index].prop],
									newCol[index].prop
								)
							}}
						</div>
						<div v-if="item.solt === 'accountStatusSolt'">
							<span
								v-if="row.loginLockStatus === 1"
								class="disableRgba"
							>
								{{ $t('report.login_lock') }}
							</span>
							<span
								v-if="row.accountLockStatus === 1"
								class="deleteRgba"
							>
								{{ $t('report.account_lock') }}
							</span>
							<span
								v-if="
									row.loginLockStatus === 0 &&
										row.accountLockStatus === 0
								"
								class="normalRgba"
							>
								{{ $t('report.normal') }}
							</span>
						</div>
						<div v-if="item.solt === 'numberSolt'">
							<p>
								{{
									handleNumber('', row[newCol[index].prop], 0)
								}}
							</p>
							<p v-if="item.subPropShow">
								{{
									handleNumber(
										'',
										row[newCol[index].subProp],
										0
									)
								}}
							</p>
						</div>
						<div v-if="item.solt === 'amountSolt'">
							<p
								v-if="item.solt === 'soltColor'"
								:style="
									handleNumberColor(row[newCol[index].prop])
								"
							>
								{{
									handleTotalNumber(
										row.currency,
										row[newCol[index].prop]
									)
								}}
							</p>
							<p v-else>
								{{ handleCurrency(row.currency) }}
								{{
									handleNumber(
										row.currency,
										row[newCol[index].prop]
									)
								}}
							</p>
						</div>
						<div v-if="item.solt === 'amountAndNumberSolt'">
							<p>
								{{ handleCurrency(row.currency) }}
								{{
									handleNumber(
										row.currency,
										row[newCol[index].prop]
									)
								}}
								<br />
								{{
									handleNumber(
										'',
										row[newCol[index].subProp],
										0
									)
								}}
							</p>
						</div>
						<div v-if="item.solt === 'amountTimeSolt'">
							<p>
								{{ handleCurrency(row.currency) }}
								{{
									handleNumber(
										row.currency,
										row[newCol[index].prop]
									)
								}}
								<br />
								{{ row[newCol[index].subProp] || '-' }}
							</p>
						</div>
						<div v-if="item.solt === 'defaultSolt'">
							<span v-if="item.isAddColor">
								<el-link
									class="lightBlueColor"
									type="primary"
									@click="dialogData(row)"
								>
									{{ $t('report.look') }}
								</el-link>
							</span>
							<span v-else>
								{{ row[newCol[index].prop] || '-' }}
							</span>
						</div>
						<div v-if="item.solt === 'proxyLevelSolt'">
							{{
								(row[newCol[index].prop] === 0
									? '0'
									: row[newCol[index].prop]) || '-'
							}}
						</div>
					</template>
				</el-table-column>
			</el-table>
			<!-- 分页 -->
			<el-pagination
				v-show="!!total"
				class="pageValue"
				:current-page.sync="pageNum"
				background
				layout="total, sizes,prev, pager, next, jumper"
				:page-size.sync="pageSize"
				:page-sizes="pageSizes"
				:total="total"
				:pager-count="9"
				@current-change="handleCurrentChange"
				@size-change="handleSizeChange"
			></el-pagination>
		</template>
		<detail-page
			v-if="showDialog"
			:rowVal="rowVal"
			:closeDialog="
				() => {
					showDialog = false
				}
			"
		/>
		<el-dialog
			:title="$t('common.row_set')"
			center
			:visible.sync="colSettings.visible"
			width="475px"
			class="setting-div"
			:before-close="cancleSetColumn"
			:close-on-click-modal="false"
		>
			<div>
				<el-link type="primary" class="mb15" @click="clickDel">
					复原缺省
				</el-link>
			</div>
			<div class="dailogContent">
				<div
					v-for="(item, index) in oldCol"
					:key="index"
					class="setting-div"
				>
					<el-checkbox v-if="index !== 0" v-model="item.isShow">
						{{ item.label }}
					</el-checkbox>
				</div>
			</div>
			<div slot="footer" class="dialog-footer footerContent">
				<el-button @click="cancleSetColumn()">
					{{ $t('common.cancel') }}
				</el-button>
				<el-button type="primary" @click="handleOrderList">
					{{ $t('common.submit') }}
				</el-button>
			</div>
		</el-dialog>
	</main-content>
</template>

<script>
import list from '@/mixins/list'
import dayjs from 'dayjs'
// import Sortable from 'sortablejs'
import { routerNames } from '@/utils/consts'
import { Storage } from '@/utils/compose'
import summaryList from './components/summaryList'
import { getColumns } from './components/columns'
import MainContent from '@/components/MainContent/index.vue'
import DatePickerShortcuts from '@/components/DatePickerShortcuts'
const start = dayjs()
	.startOf('day')
	.valueOf()
const end = dayjs()
	.endOf('day')
	.valueOf()
const setSearchTime = () => [
	dayjs()
		.startOf('day')
		.valueOf(),
	dayjs()
		.endOf('day')
		.valueOf()
]
export default {
	name: routerNames.proxyReport,
	components: {
		DetailPage: () => import('./components/detail-page.vue'),
		MainContent,
		DatePickerShortcuts
	},
	mixins: [list, summaryList],
	data() {
		return {
			tableHeight: 480,
			otherDependenComponents: [],
			queryData: {},
			searchTime: [start, end],
			// registerTime: [start, end],
			dateFlag: '0',
			isAllData: false,
			tableData: [],
			subSummary: {},
			totalSummary: {},
			showDialog: false,
			exportBtnLoading: false,
			rowVal: {},
			merchantObj: '',
			axiosDate: '',
			loading: false,
			oldCol: [],
			dropCol: [],
			newCol: [],
			colSettings: {
				visible: false
			},
			// 拖拽状态
			dragState: {
				start: -3, // 起始元素的 index 防止初始化cellStyle时序号、展开等默认样式改变，最好小于-3
				end: -3, // 移动鼠标时所覆盖的元素 index
				dragging: false, // 是否正在拖动
				direction: undefined // 拖动方向
			},
			headKey: 'proxyReport', // 表头数组变换位置时，重绘table（不更新该值，表头数组变化时，页面不会改变）
			scrollX: 0 // 初始x轴scroll位置（用于定位X轴滚动条）
		}
	},
	computed: {
		accountTypeArr() {
			return this.globalDics.reportAccountType || []
		}
	},
	watch: {
		oldCol: {
			handler(newVal) {
				if (newVal) {
					setTimeout(() => {
						this.newCol = newVal.filter((its) => {
							return its.isShow === true
						})
					}, 1000)
				}
			},
			deep: true
		},
		dateFlag: {
			handler(newVal) {
				if (newVal === '1') {
					this.isAllData = true
				} else {
					this.isAllData = false
				}
			}
		},
		$route: function(to, from) {
			if (to.path.indexOf(routerNames.proxyReport) > -1) {
				this.getRouteQuery(true)
			}
		}
	},
	created() {
		this.$store.dispatch('user/updateCurrentAccountPeriod')
		const storageColumn = this.getSaveTableData()
		this.dropCol = getColumns()
		const uu_Id = this.$store.state.user.userInfo?.id
		this.oldCol =
			storageColumn &&
			storageColumn[`${uu_Id}_commonTableKey_proxyReport`]
				? storageColumn[`${uu_Id}_commonTableKey_proxyReport`]
				: this.dropCol
		this.newCol = this.oldCol
		this.getRouteQuery()
	},
	mounted() {},
	methods: {
		handleShortcutBtnClick(val) {
			this.searchTime = val
			this.loadData()
		},
		// 路由跳转
		getRouteQuery(isLoadData = false) {
			if (this.$route.query?.userName) {
				this.queryData = {
					proxyName: this.$route.query?.userName
				}
				this.dateFlag = '0'
				this.searchTime = [
					this.$route.query?.startDate || start,
					this.$route.query?.endDate || end
				]
				this.$router.replace({ query: {} })
				if (isLoadData) {
					this.loadData()
				}
			}
		},
		// 鼠标摁下触发
		handleMounseDown(e, column, $index) {
			this.dragState.dragging = true
			this.dragState.start = parseInt($index - 0)
			// 添加鼠标抬起事件  消除鼠标摁下立刻松开问题
			document.addEventListener('mouseup', this.handleMouseUp)
			// 添加拖拽结束事件
			document.addEventListener('dragend', this.handleMouseUp)
			// 对选中的表头允许其拖拽
			const dragclass = '.el-table__header-wrapper .' + column.id
			const dragDom = document.querySelectorAll(dragclass)
			dragDom.forEach((dom) => {
				// 允许表头块可以被拖拽 draggable 属性 不允许拖拽dragover等相关拖拽事件无法触发
				dom.setAttribute('draggable', true)
			})
		},
		/** 鼠标在拖拽移动时触发 */
		handleDragover(e, column, $index) {
			if (this.dragState.dragging) {
				// 获取当前滚动条的位置
				const scrollDom = this.$refs.elTable.bodyWrapper
				this.scrollX = scrollDom.scrollLeft
				const index = parseInt($index - 0) // 记录起始列
				/** 实时更改鼠标处于表头的位置 */
				if (index - this.dragState.start !== 0) {
					this.dragState.direction =
						index - this.dragState.start < 0 ? 'left' : 'right' // 判断拖动方向
					this.dragState.end = parseInt($index - 0)
				} else {
					this.dragState.end = this.dragState.start
					this.dragState.direction = null
				}
			}
		},
		/** 鼠标抬起或拖拽结束触发 */
		handleMouseUp() {
			// 更新拖拽后的表头
			this.headDraged(this.dragState)
			const { end } = this.dragState
			// 初始化拖动状态
			this.dragState = {
				start: end, // 记录最后拖动的位置
				end: -9,
				dragging: false,
				direction: undefined
			}
			document.removeEventListener('mouseup', this.handleMouseUp)
			document.removeEventListener('dragend', this.handleMouseUp)
			setTimeout(() => {
				// 重置拖拽状态
				this.dragState.start = -9
			}, 500)
		},
		// 更新拖拽后的表头
		headDraged({ start, end, direction }) {
			if (direction) {
				const originColumn = this.newCol[start]
				// 有位置交换时，原先位置的元素删除，再在目标处插入
				this.oldCol.splice(start, 1)
				this.oldCol.splice(end, 0, originColumn)
				this.headKey = new Date().getTime() + '' // 更新table key值
				const uu_Id = this.$store.state.user.userInfo.id
				const uidKey = uu_Id + '_commonTableKey_proxyReport'
				const getLocalTableData = Storage.get('commonTableKey')
				if (getLocalTableData) {
					Storage.set(
						'commonTableKey',
						Object.assign(getLocalTableData, {
							[uidKey]: this.oldCol
						})
					)
				} else {
					Storage.set('commonTableKey', {
						[uidKey]: this.oldCol
					})
				}
				this.$nextTick(() => {
					// 因为表头重绘后滚动条会移到最左端初始位置，因此如果是在中间部分拖拽，还需要把滚动条在定位到该位置
					this.$refs.elTable.bodyWrapper.scrollLeft = this.scrollX
				})
			}
		},
		// 拖动虚线样式设置
		cellClassName({ columnIndex }) {
			const { start, end, direction } = this.dragState
			const target = columnIndex - 0
			if (target === start) {
				// 被移动的元素
				return 'drag_start'
			} else if (target === end) {
				// 要移动的位置
				return `drag_end_${direction}`
			}
			return ''
		},
		changeTableSort({ column, prop, order }) {
			this.queryData.orderKey = prop
			if (order === 'ascending') {
				// 升序
				this.queryData.orderType = 'asc'
			} else if (column.order === 'descending') {
				// 降序
				this.queryData.orderType = 'desc'
			} else {
				delete this.queryData.orderKey
				delete this.queryData.orderType
			}
			this.loadData()
		},
		loadData() {
			if (+new Date() - 500 < this.axiosDate) return
			const timeArr = this.searchTime || []
			// const registerArr = this.registerTime || []
			const params = {
				...this.queryData,
				queryWay: Number(this.dateFlag),
				startTime:
					this.dateFlag === '0'
						? dayjs(timeArr[0]).format('YYYY-MM-DD')
						: undefined,
				endTime:
					this.dateFlag === '0'
						? dayjs(timeArr[1]).format('YYYY-MM-DD')
						: undefined,
				...this.getParams()
			}
			// params.registerStartTime = registerArr[0]
			// 	? dayjs(registerArr[0]).format('YYYY-MM-DD')
			// 	: ''
			// params.registerEndTime = registerArr[1]
			// 	? dayjs(registerArr[1]).format('YYYY-MM-DD')
			// 	: ''
			// const min = dayjs(timeArr[0])
			// const max = dayjs(timeArr[1])
			// const day = dayjs(max).diff(min, 'day')
			// const registerMin = dayjs(registerArr[0])
			// const registerMax = dayjs(registerArr[1])
			// const registerDay = dayjs(registerMax).diff(registerMin, 'day')
			// if (day >= 31 && this.dateFlag === '0') {
			// 	this.$message.warning(this.$t('report.31_day'))
			// 	this.total = 0
			// 	return
			// }
			// if (registerDay >= 92) {
			// 	this.$message.warning(this.$t('report.92_day'))
			// 	this.total = 0
			// 	return
			// }
			this.loading = true
			this.pageCurrency = this.merchantObj?.currency || ''
			this.$api
				.getReportProxyReportList(params)
				.then((res) => {
					this.loading = false
					this.axiosDate = +new Date()
					if (res.code === 200) {
						this.tableData = []
						this.tableData = res?.data?.record || []
						this.total = res?.data?.totalRecord || 0
						this.subSummary = res?.data?.summary || {}
					}
				})
				.catch(() => {
					this.loading = false
				})
			this.$api
				.getReportProxyReportSummary(params)
				.then((res) => {
					this.loading = false
					if (res.code === 200) {
						this.totalSummary = res?.data || {}
					}
				})
				.catch(() => {
					this.loading = false
				})
		},
		dialogData(val) {
			const timeArr = this.searchTime || []
			this.rowVal = {
				proxyId: val.proxyId,
				currency: val.currency,
				merchantId: val.merchantId,
				proxyAccount: val.proxyAccount,
				queryWay: Number(this.dateFlag),
				startTime:
					this.dateFlag === '0'
						? dayjs(timeArr[0]).format('YYYY-MM-DD')
						: undefined,
				endTime:
					this.dateFlag === '0'
						? dayjs(timeArr[1]).format('YYYY-MM-DD')
						: undefined
			}
			this.showDialog = true
		},

		reset() {
			this.pageNum = 1
			this.queryData = {}
			this.searchTime = setSearchTime()
			// this.registerTime = [start, end]
			this.dateFlag = '0'
			this.merchantObj = ''
			if (this.$refs.elTable) {
				this.$refs.elTable.clearSort()
			}
			this.loadData()
		},
		handleExportExcel() {
			const timeArr = this.searchTime || []
			// const registerArr = this.registerTime || []
			const params = {
				...this.queryData,
				startTime:
					this.dateFlag === '0'
						? dayjs(timeArr[0]).format('YYYY-MM-DD')
						: undefined,
				endTime:
					this.dateFlag === '0'
						? dayjs(timeArr[1]).format('YYYY-MM-DD')
						: undefined,
				queryWay: Number(this.dateFlag)
			}
			// params.registerStartTime = registerArr[0]
			// 	? dayjs(timeArr[0]).format('YYYY-MM-DD')
			// 	: ''
			// params.registerEndTime = registerArr[1]
			// 	? dayjs(timeArr[1]).format('YYYY-MM-DD')
			// 	: ''
			// const min = dayjs(timeArr[0])
			// const max = dayjs(timeArr[1])
			// const day = dayjs(max).diff(min, 'day')
			// if (day >= 31 && this.dateFlag === '0') {
			// 	this.$message.warning(this.$t('report.31_day'))
			// 	return
			// }
			this.exportBtnLoading = true
			this.exportExcelPublic({
				api: 'getReportProxyReportExport',
				params
			}).finally(() => {
				this.exportBtnLoading = false
			})
		},
		// 提交列设置数据
		handleOrderList() {
			this.colSettings.visible = false
			const uu_Id = this.$store.state.user.userInfo.id
			const uidKey = uu_Id + '_commonTableKey_proxyReport'
			const getLocalTableData = Storage.get('commonTableKey')
			if (getLocalTableData) {
				Storage.set(
					'commonTableKey',
					Object.assign(getLocalTableData, {
						[uidKey]: this.oldCol
					})
				)
				this.oldCol = getLocalTableData[uidKey]
			} else {
				Storage.set('commonTableKey', {
					[uidKey]: this.oldCol
				})
			}
		},
		// 打开列设置弹框
		openColSettings() {
			this.colSettings.visible = true
		},
		// 取消列设置
		cancleSetColumn() {
			this.colSettings.visible = false
			const getLocalTableData = Storage.get('commonTableKey')
			const uu_Id = this.$store.state.user.userInfo.id
			const uidKey = uu_Id + '_commonTableKey_proxyReport'
			if (getLocalTableData && getLocalTableData[uidKey]) {
				this.oldCol = getLocalTableData[uidKey]
			} else {
				this.oldCol.map((item, index) => {
					item.isShow = true
				})
			}
		},
		// 复原缺省
		clickDel() {
			this.oldCol.map((item, index) => {
				item.isShow = true
			})
		}
	}
}
</script>

<style lang="scss" scoped>
.dailogContent {
	height: 400px;
	overflow-y: auto;
	position: relative;
}
.footerContent {
	position: sticky;
	z-index: 10;
	bottom: 32px;
}
.tips-box {
	position: absolute;
	right: 10px;
	top: 50%;
	margin-top: -12px;
}
::v-deep .el-dialog__header {
	color: #909399;
	font-weight: 700;
}
::v-deep .el-range-editor.el-input__inner {
	padding: 1px 10px;
}
::v-deep .el-table__fixed-footer-wrapper .cell,
::v-deep .el-table__footer-wrapper .cell {
	height: 100%;
	padding: 0 !important;
	margin: 0 !important;
	> div {
		height: 100%;
	}
}
::v-deep .footer_count_row {
	min-height: 50px;
	height: 50%;
	display: flex;
	font-weight: 700;
	padding: 5px 0;
	align-items: center;
	flex-direction: column;
	justify-content: center;
}
::v-deep .footer_count_row_border {
	border-top: 1px solid #ebeef5;
}
::v-deep .el-table__header-wrapper .cell {
	display: flex !important;
	align-items: center !important;
	justify-content: center !important;
}
</style>
